<?php
namespace App\Service\ApiXcx;

use Illuminate\Support\Facades\DB;

class CouponService extends BaseService
{
    //会员劵

    protected $scences = [
        '全场通用'
    ];
    protected $statuss = [
        '', '未领取', '已领取未使用', '已过期', '已使用',
    ];
    protected $types = [
        1 => '新用户可得', '充值可得',
    ];

    /**
     * 可用列表
     * @param array $pages【start，limit】
     * @param int $uid
     * @param int $is_use 是否可用：1可用，2失效
     * @return array
     */
    public function getList($pages, $uid, $is_use = 0)
    {
        $this->guoqi();
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbUcoupon)
            ->where('uid', $uid)
            ->where('expire', '>=', toDate());
        if ($is_use == 1) {
            $db = $db->where('status', 2);
        } else if ($is_use == 2) {
            $db = $db->where('status', '>', 2);
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => [], 'total' => 0);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //场景
            $scenes = $this->scences;
            $sceneName = array_key_exists($v['scene'], $scenes) ? $scenes[$v['scene']] : '';
            //状态
            $statuss = $this->statuss;
            $statusName = array_key_exists($v['status'], $statuss) ? $statuss[$v['status']] : '';
            $shop_time = '';
            if ($is_use == 1) {
                $shop_time = $v['expire'] . '前可使用';
            } else if ($is_use == 2) {
                $shop_time = $v['status']==3 ? '已过期' : '已使用';
            }
            $status = $v['status'];
            if (strtotime($v['expire']) < time()) {
                $shop_time = '已过期';
                $statusName = '已过期';
                $status = 3;
            }
            $arys[] = [
                'id' => $v['id'],
                'title' => $sceneName . '，减' . toNumber($v['reduce']),
                'desc' => '满' . toNumber($v['full']) . '可用',
                'stop_time' => $shop_time,
                'quata' => toNumber($v['quata']),
                'scene' => $v['scene'],
                'scene_name' => $sceneName,
                'full' => toNumber($v['full']),
                'reduce' => toNumber($v['reduce']),
                'opentime' => $v['opentime'],
                'expire' => $v['expire'],
                'status' => $status,
                'status_name' => $statusName,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    //看看有没有过期
    public function guoqi()
    {
        DB::table($this->dbUcoupon)->where('status', '<', 3)
            ->where('expire', '<', toDate())
            ->update(['status' => 3, 'expiretime' => toDate()]);
    }

    /**
     * 领取劵
     * @param int $id 会员劵ID
     */
    public function apply($uid, $id)
    {
        $res = (array) DB::table($this->dbUcoupon)
            ->where('uid', $uid)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '会员劵不存在');
        }
        if ($res['opentime'] != '' && $res['opentime'] < toDate()) {
            return array('code' => -2, 'msg' => '还未到领取的时间');
        }
        if ($res['status'] > 1) {
            return array('code' => -2, 'msg' => '已领取过');
        }
        $up = DB::table($this->dbUcoupon)
            ->where('id', $id)
            ->update([ 'status' => 2, 'applytime' => toDate() ]);
        if (!$up) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 获取
     * @param int $uid
     * @param int $amount
     */
    public function getOne($uid, $amount)
    {
        $res = (array) DB::table($this->dbUcoupon)
            ->where('uid', $uid)
            ->where('status', 2)
            ->where('full', '>=', $amount)
            ->orderBy('id', 'asc')
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '没有可用的会员劵');
        }
        if ($res['expire'] < toDate()) {
            return array('code' => -2, 'msg' => '已过期');
        }
        $arys = [
            'id' => $res['id'],
            'quata' => $res['quata'],
        ];
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 获取选项列表
     * @param int $uid
     * @param int $amount
     */
    public function getOption($uid, $amount)
    {
        $db = DB::table($this->dbUcoupon)
            ->where('uid', $uid)
            ->where('status', 2)
            ->where('expire', '>=', toDate())
            ->where('full', '<=', $amount*100)
            ->where('quata', '<=', $amount*100);
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有可用的会员劵', 'data' => [], 'total' => $total);
        }
        $scenes = $this->scences;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $scene_name = array_key_exists($v['scene'], $scenes) ? $scenes[$v['scene']] : '';
            $full = toNumber($v['full']);
            $reduce = toNumber($v['reduce']);
            $quata = toNumber($v['quata']);
            $arys[] = [
                'id' => $v['id'],
                'title' => $scene_name . '，满' . $full. '减' . $reduce,
                'quata' => $quata,
                'expire' => $v['expire'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 获取新用户优惠劵列表
     * @param int $uid
     */
    public function getNewUserList($uid)
    {
        $uOne = (array) $this->dbConn($this->dbUser)->where('id', $uid)->first();
        if (empty($uOne)) {
            return $this->toback(-2, '用户不存在');
        }
//        if ($uOne['is_new'] == 0) {
//            return $this->toback(-2, '不是新用户');
//        }
        $res = DB::table($this->dbUcouponTmp)
            ->where('del', 0)->where('type', 1)
            ->skip(0)->take(3)
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有设置新用户优惠劵', 'data' => []);
        }
        $scenes = $this->scences;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $scene_name = array_key_exists($v['scene'], $scenes) ? $scenes[$v['scene']] : '';
            $uc = $this->dbConn($this->dbUcoupon)
                ->where('tmp_id', $v['id'])
                ->where('uid', $uid)
                ->where('status', '>', 1)
                ->first();
            $arys[] = [
                'id' => $v['id'],
//                'title' => $scene_name . '+' . $v['reduce'] . '满减',
//                'title' => $scene_name . '满' . toNumber($v['quata']) . '金额减' . toNumber($v['reduce']) . '金额',
                'title' => '全场通用',
                'full' => toNumber($v['full']),
                'reduce' => toNumber($v['reduce']),
                'quata' => toNumber($v['quata']),
                'is_apply' => $uc ? 1 : 0,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    //领取新用户优惠劵
    public function addNewUser($uid, $id)
    {
        $uOne = (array) $this->dbConn($this->dbUser)->where('id', $uid)->first();
        if (empty($uOne)) {
            return $this->toback(-2, '用户不存在');
        }
        if ($uOne['is_new'] == 0) {
            //return $this->toback(-2, '不是新用户');
            return $this->toback(-2, '仅新用户可领');
        }
        $resOne = (array) DB::table($this->dbUcoupon)
            ->where('uid', $uid)
            ->where('tmp_id', $id)
            ->first();
        if (!empty($resOne)) {
            return array('code' => -2, 'msg' => '已领取未使用');
        }
        $res = (array) DB::table($this->dbUcouponTmp)
            ->where('del', 0)->where('type', 1)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该优惠劵错误');
        }
        $expire = time() + 3600 * 24 *$res['expire'];
        $cData = [
            'uid' => $uid,
            'tmp_id' => $id,
            'type' => $res['type'],
            'bg' => $res['bg'],
            'quata' => $res['quata'],
            'scene' => $res['scene'],
            'full' => $res['full'],
            'reduce' => $res['reduce'],
            'opentime' => $res['opentime'],
            'expire' => date('Y-m-d H:i:s', $expire),
            'status' => 2,
            'addtime' => toDate(),
        ];
        $lastid = DB::table($this->dbUcoupon)->insertGetId($cData);
        if (!$lastid) {
            return array('code' => -1, 'msg' => 'fail');
        }
        return array('code' => 0, 'msg' => 'success');
    }
}